package br.com.ffm.praticas.facade;

import java.sql.SQLException;

import br.com.ffm.praticas.bean.Address;
import br.com.ffm.praticas.dao.AddressDAO;

public class AddressFACADE {
	
	private static AddressFACADE addressFacade;
	private static AddressDAO addressDAO;
	
	/**
	 * Constructor of AddressFACADE
	 */
	private AddressFACADE(){
		addressDAO = new AddressDAO();
	}
	
	/**
	 * Method that returns an unique instance of AddressFACADE
	 * @return An instance of AddressFACADE
	 */
	public static AddressFACADE getInstance(){
		if(addressFacade == null){
			addressFacade = new AddressFACADE();
		}
		return addressFacade;
	}
	
	/**
	 * Method that test if an address exist
	 * @param address The address to be tested
	 * @return If the address exist, returns true else returns false
	 * @throws SQLException 
	 */
	private boolean alreadyExist(Address address) throws SQLException{
		if(address != null){
			Address a = addressDAO.getAddress(address.getId());
			if (a != null)
				return true;
			else
				return false;
		}
		return false;
	}
	
	/**
	 * Method that add a new Address
	 * @param address Address to be added
	 * @return if add the address returns true, else returns false
	 * @throws SQLException 
	 */
	public boolean insert(Address address) throws SQLException{
		if(address != null && !alreadyExist(address)){
			addressDAO.insert(address);
			return true;
		}
		return false;
	}
	
	/**
	 * Method that remove an address
	 * @param address the address to be removed
	 * @return if remove the address returns true, else  returns false
	 * @throws SQLException 
	 */
	public boolean delete(Address address) throws SQLException{
		if(address != null && alreadyExist(address)){
			addressDAO.delete(address);
			return true;
		}
		return false;
	}
	
	/**
	 * Method that search an address by ID
	 * @param id The id of the address to be found
	 * @return If found the address return it, else return NULL
	 * @throws SQLException 
	 */
	public Address getAddress(int id) throws SQLException{
		return addressDAO.getAddress(id);
	}
	
	/**
	 * Method that update an address
	 * @param address The address with the new attributes to be updated
	 * @return If update the address returns true, else returns false
	 */
	public boolean update(Address address){
		if (address != null) {
			addressDAO.update(address);
		}
		return false;
	}
	
	/**
	 * Method that count the number of addresses
	 * @return The number of addresses
	 * @throws SQLException 
	 */
	public int count() throws SQLException{
		return addressDAO.getAddresses().size();
	}

}
